package com.qf.votesystem.websocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/webSocket/{count}")
@Slf4j
public class WebSocketServer {

    private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    private static String countTotal;

    /**前端发送请求建立websocket连接，就会执行@OnOpen方法**/
    @OnOpen
    public void open( @PathParam("count") String count,Session session) throws IOException {
        countTotal = count;
        sessionMap.put(countTotal,session);
    }

    /**
     * 当客户端发消息时，服务端如何处理
     */
    @OnMessage
    public void onMsg(Session session,String msg) throws IOException {

        log.debug("收到客户端发下来的消息：{}",msg);

        session.getBasicRemote().sendText("from server" + msg);

    }

    /**前端关闭页面或者主动关闭websocket连接，都会执行close**/
    @OnClose
    public void close(@PathParam("count") String count){
        sessionMap.remove(countTotal);
    }

    /**
     * 链接出错
     * @param throwable
     */
    @OnError
    public void onError(Throwable throwable){
        log.debug("{}人数统计出现问题",throwable);
    }

    /**
     *
     * @param
     * @param msg
     */

    public static void sendMsg(String msg) throws IOException {

            Session session = sessionMap.get(countTotal);
            session.getBasicRemote().sendText(msg);
    }
}
